//
//  WmcUploadGridView.swift
//  YPWatermarkCamera
//
//  Created by 马涛 on 2022/6/21.
//

import RxRelay
import UIKit
import YPBedrock

// MARK: - [WmcUploadGridView]

class WmcUploadGridView: WmcBaseView {
    // Lifecycle

    /// 构造方法
    /// - Parameters:
    ///   - row: 行
    ///   - column: 列
    convenience init(row: CGFloat, column: CGFloat) {
        self.init(frame: .zero)
        self.row = row
        self.column = column
        self.collectionView.reloadData()
    }

    // Internal

    /// 占位模型 添加按钮
    static var noneImgModel: WmcUploadGridModel {
        let model = WmcUploadGridModel()
        model.style = .add
        return model
    }

    /// 行
    var row: CGFloat = 2
    /// 列
    var column: CGFloat = 4

    var models: [WmcUploadGridModel] = [noneImgModel]

    /// 选中的图片
    var selectedModels: BehaviorRelay<[UIImage]> = .init(value: [])

    lazy var collectionView: UICollectionView = {
        let view = UICollectionView(frame: .zero, collectionViewLayout: self.layout)
        view.backgroundColor = UIColor.wmc_white_FFFFFF
        view.delegate = self
        view.dataSource = self
        view.register(WmcUploadGridCell.self, forCellWithReuseIdentifier: "cell")
        return view
    }()

    lazy var layout: UICollectionViewFlowLayout = {
        let lay = UICollectionViewFlowLayout()
        lay.minimumLineSpacing = vSpace
        lay.minimumInteritemSpacing = hSpace
        lay.itemSize = CGSize(width: itemWidth, height: itemWidth)
        return lay
    }()

    /// 最大数
    var maxCount: Int {
        return Int(row * column)
    }

    /// 宽
    var itemWidth: CGFloat {
        return (Wmc_screenWidth - 26 - (column - 1) * hSpace) / column
    }

    /// 垂直space
    var vSpace: CGFloat {
        return 10
    }

    /// 水平space
    var hSpace: CGFloat {
        return 10
    }

    override func makeUI() {
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.left.bottom.right.equalToSuperview()
            make.height.equalTo(self.computeCollectionH())
        }
    }

    // Private

    /// 更新 collectionview 约束
    /// - Returns: description
    private func refreshUpdateCollectionHeight() {
        collectionView.snp.remakeConstraints { make in
            make.top.left.bottom.right.equalToSuperview()
            make.height.equalTo(self.computeCollectionH())
        }
    }

    /// 计算collectionview height
    /// - Returns: description
    private func computeCollectionH() -> CGFloat {
        return itemWidth * getDynamicRow() + (getDynamicRow() - 1) * vSpace
    }

    /// 获取动态行数
    /// - Returns: description
    private func getDynamicRow() -> CGFloat {
        let row = CGFloat(models.count) / column
        let last = models.count % Int(column)
        let totalRow = row + (last > 0 ? 1 : 0)
        return totalRow
    }

    /// 计算collectionview 最大高度
    /// - Returns: description
    private func computeCollectionMaxH() -> CGFloat {
        return itemWidth * row + (row - 1) * vSpace
    }

    /// 外部传值
    /// - Returns: description
    private func sendSelectedImgs() {
        var selectedImgModels = self.models.yp.copy
        selectedImgModels.removeLast()
        let imgs = selectedImgModels.compactMap { $0.image }
        self.selectedModels.accept(imgs)
    }
}

// MARK: - UICollectionViewDelegate, UICollectionViewDataSource

extension WmcUploadGridView: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.models.count > 6 {
            return 6
        } else {
            return self.models.count
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! WmcUploadGridCell
        if let model = self.models.yp.object(at: indexPath.row) {
            cell.configModel(model, indexPath: indexPath)
        }
        cell.delClosure = { [weak self] (img, indexPath) in
            self?.models.removeAll() { $0.image == img.image }
            self?.sendSelectedImgs()
            self?.collectionView.reloadData()
        }
        cell.addClosure = { [weak self] img in
            self?.showSelectPhoto()
        }
        return cell
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate

extension WmcUploadGridView: UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
        picker.dismiss(animated: true, completion: nil)
        let key = UIImagePickerController.InfoKey(rawValue: "UIImagePickerControllerOriginalImage")
        guard let image = info[key] as? UIImage else { return }
        let model = WmcUploadGridModel()
        model.image = image
        model.style = .image
        models.insert(model, at: 0)
        self.collectionView.reloadData()
        self.refreshUpdateCollectionHeight()
        self.sendSelectedImgs()
    }
}

extension WmcUploadGridView {
    /// action sheet
    private func showSelectPhoto() {
        let sheet = WmcSheetView()
        sheet.title = "上传照片"
        sheet.items = ["拍照", "相册"]
        sheet.show(height: 250)
        sheet.didSelectIndexBlock = { [weak self] index in
            guard let weakSelf = self else { return }
            switch index {
            case 0:
                let cameraStatus = WmcAuthorizedManager.camera()
                if cameraStatus.info.isAvailable {
                    weakSelf.takePhoto()
                } else {
                    WmcAuthorizedManager.showCameraPermissionAlert()
                }
            case 1:
                let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
                if photoAlbumStatus.info.isAvailable {
                    weakSelf.selectPhoto()
                } else {
                    WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                }
            default: break
            }
        }
    }

    /// 拍照
    private func takePhoto() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .camera
        YPApp.CurrentVC?.present(imagePicker, animated: true, completion: nil)
    }

    /// 选择照片
    private func selectPhoto() {
        let selectedCount = self.models.count - 1
        let maxCount = 6
        let currentMaxCount = maxCount - selectedCount
        WmcPhotoSelectManager.photoSelect(vc: YPApp.CurrentVC, maxCount: currentMaxCount) { [weak self] imgs in
            guard let weakSelf = self else { return }
            imgs.forEach { img in
                let model = WmcUploadGridModel()
                model.image = img
                model.style = .image
                weakSelf.models.insert(model, at: 0)
            }
            weakSelf.collectionView.reloadData()
            weakSelf.refreshUpdateCollectionHeight()
            weakSelf.sendSelectedImgs()
        }
    }
}
